package com.zhilianbao.leyaogo.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.ThreadPool;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.model.response.UserLoginInfo;
import com.zhilianbao.leyaogo.ui.activity.base.BaseOkHttpActivity;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.AwesomeEditTextView;
import com.zhilianbao.leyaogo.view.widgets.DelayButton;
import com.zlb.lxlibrary.service.LeXiuInitService;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.zhilianbao.ice.service.IceService;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by gyt on 2017/3/2
 * 快捷登录页面
 */
public class QuickLoginActivity extends BaseOkHttpActivity {


    @BindView(R.id.edt_login_phone)
    AwesomeEditTextView mEdtLoginPhone;
    @BindView(R.id.edt_login_verify_code)
    AwesomeEditTextView mEdtLoginVerifyCode;
    @BindView(R.id.btn_delay)
    DelayButton mBtnDelay;
    @BindView(R.id.tv_login)
    TextView mTvLogin;
    @BindView(R.id.tv_use_password)
    TextView mTvUsePassword;
    @BindView(R.id.tv_register)
    TextView mTvRegister;
    private int logicState;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_quick_login;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initToolbar(getString(R.string.quick_login));
        if (getIntent().getExtras() != null) {
            logicState = getIntent().getExtras().getInt(IntentConfig.LOGIC_CODE, 0);
        }
        mTvLogin.setEnabled(false);
        mEdtLoginPhone.addTextChangedListener(MyTextWatcher);
        mEdtLoginVerifyCode.addTextChangedListener(MyTextWatcher);
        mEdtLoginPhone.setText(Utils.getUserLoginName());
    }

    @OnClick({R.id.btn_delay, R.id.tv_login, R.id.tv_use_password, R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_delay:
                if (verifyMobilePhone())
                    sendVerifyCode(mEdtLoginPhone.getText().toString().trim());
                break;
            case R.id.tv_login:
                if (verifyMobilePhone())
                    login(mEdtLoginPhone.getText().toString().trim(), mEdtLoginVerifyCode.getText().toString().trim());
                break;
            case R.id.tv_use_password:
                Utils.startLogin(logicState);
                finish();
                break;
            case R.id.tv_register:
                Utils.startActivity(this, RegisterActivity.class);
                break;
        }
    }

    private boolean verifyMobilePhone() {
        final String phone = mEdtLoginPhone.getText().toString().trim();
        if (CheckUtils.isEmpty(phone)) {
            XToastUtils.showShortToast(getString(R.string.msg_login_input_mobile));
            return false;
        }

        if (phone.length() != 11) {
            XToastUtils.showShortToast(R.string.wrong_phone_length);
            return false;
        }

        if (!Utils.isPhoneNumber(phone)) {
            XToastUtils.showShortToast(R.string.wrong_phone_format);
            return false;
        }

        if (!CheckUtils.isMobilePhone(phone)) {
            XToastUtils.showShortToast(R.string.invalid_phone_number);
            return false;
        }
        return true;

    }

    /**
     * 手机号验证码登录 若未注册则自动注册
     */
    private void login(String mobile, String code) {
        AccountApi.login(this, 1, mobile, code, new DialogCallback<UserLoginInfo>(this, getResources().getString(R.string.hint_logining)) {

            @Override
            public void onSuccess(UserLoginInfo userLoginInfo, Call call, Response response) {
                if (userLoginInfo == null) {
                    XToastUtils.showShortToast(R.string.unregistered_phone);
                } else {
                    //登录成功保存用户信息
                    Utils.putUserLoginInfo(userLoginInfo);
                    Utils.putUserLoginName(mobile);
                    XToastUtils.showShortToast(R.string.login_suc);
                    //登录成功初始化ICE
                    IceService.getInstance().initIce();
                    //                    Utils.registerPush();
                    LeXiuInitService.getInstance().onLegoLoginSuccess(userLoginInfo.getUserId() + "", userLoginInfo.getUserAlias(), Utils.returnUrlShow(userLoginInfo.getUserPic()), userLoginInfo.getTokenId(), Utils.getSupplierId() + "");
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_LOGIN_SUCCESS));
                    ThreadPool.postOnUiDelayed(() -> LogicCodeBlock.create().dispatchLogicCode(logicState), 500);
                    finish();
                }
            }

        });
    }

    /**
     * 发送验证码请求
     */
    private void sendVerifyCode(String mobile) {

        AccountApi.sendVerifyCode(this, mobile, new DialogCallback<Object>(this) {

            @Override
            public void onSuccess(Object o, Call call, Response response) {
                XToastUtils.showShortToast(getString(R.string.send_verify_code_suc));
                // 重新获取光标
                mEdtLoginVerifyCode.requestFocus();
                mBtnDelay.startCountDown();
            }

        });
    }


    private TextWatcher MyTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            enableButton();
        }
    };

    /**
     * 判断按钮是否可点击
     */
    private void enableButton() {
        mBtnDelay.setEnabledGo(mEdtLoginPhone.getText().length() != 0);
        mTvLogin.setEnabled(mEdtLoginPhone.getText().length() != 0 && mEdtLoginVerifyCode.getText().length() != 0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mEdtLoginPhone.clearFocus();
        mEdtLoginVerifyCode.clearFocus();
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        // 注册手机号存在时，从RegisterActivity跳转回来
        if (eventManager.getEventCode() == LeEventCode.MSG_CODE_BACK_TO_LOGIN_ACTIVITY) {
            mEdtLoginPhone.setText(Utils.getUserLoginName());
        } else if (eventManager.getEventCode() == LeEventCode.MSG_CODE_LOGIN_SUCCESS || eventManager.getEventCode() == LeEventCode.MSG_CODE_GO_TO_LOGIN_BY_LEXIU) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MyTextWatcher != null) {
            mEdtLoginVerifyCode.removeTextChangedListener(MyTextWatcher);
            mEdtLoginPhone.removeTextChangedListener(MyTextWatcher);
            MyTextWatcher = null;
        }
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return true;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return TransitionMode.FADE;
    }

    @Override
    public void leftContainerClick() {
        super.leftContainerClick();
        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_CLICK_NOT_LOGIN_BACK));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
